package service

import (
	"context"
	"encoding/json"
	"fmt"
	grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
	"google.golang.org/grpc"
	"net"
	"os"
	"os/signal"
	"syscall"
	"week13/api/proto"
	"week13/cmd"
	"week13/configs"
	"week13/errors"
	"week13/internal/biz/deal"
	"week13/log"
	"week13/metrics"
	"week13/pkg/orm"
)

type AdminService struct {
}
//收入列表
func (srv *AdminService) Incomes(ctx context.Context, request *proto.AdminIncomeRequest) (*proto.IncomesResponse, error) {
	return nil,nil
}
//订单列表
func (srv *AdminService) Deals(ctx context.Context, request *proto.AdminDealRequest) (*proto.DealsResponse, error) {
	ctx.Value("uid")
	where := deal.NewDealWhere()
	if request.DealId > 0 {
		where.DealId = orm.CreateOp("=",request.DealId)
	}
	if request.AgentId>0 {
		where.AgentId = orm.CreateOp("=",request.AgentId)
	}
	if request.State >0 {
		where.State = orm.CreateOp("=",request.State)
	}
	genTimeWhere := []interface{}{}

	if request.StartTime >0 {
		genTimeWhere = append(genTimeWhere,orm.CreateOp(">",request.StartTime))
	}
	if request.EndTime>0 {
		genTimeWhere = append(genTimeWhere,orm.CreateOp("<",request.EndTime))
	}
	if len(genTimeWhere)>0 {
		where.GenTime = genTimeWhere
	}
	page := 1
	pageSize := 10
	if request.Page>0{
		page = int(request.Page)
	}
	if request.PageSize>0{
		pageSize = int(request.PageSize)
	}
	var result *proto.DealsResponse = &proto.DealsResponse{}
	data,total,err := deal.ListByWhere(where,page,pageSize)
	if err != nil {
		fmt.Println(err.Error())
		result.Code = errors.Code(err)
		result.Message = "internal error"
		metrics.IncrServerRequest("admin/Deals",result.Code)
		return result,nil
	}
	deals := &proto.Deals{
		List:  nil,
		Count: 0,
	}
	result.Data = deals
	if total<1{
		return result,nil
	}
	var list []*proto.Deal
	deals.Count = int32(total)
	jsonData, err := json.Marshal(data)
	if err != nil {
		metrics.IncrServerRequest("admin/Deals",errors.JSON_FAIL)
		return nil,err
	}
	err = json.Unmarshal(jsonData,&list)
	if err != nil {
		log.Info("transfer json data:%s,err:%s",jsonData,err.Error())
		result.Code = errors.JSON_FAIL
		result.Message = errors.JSON_FAIL_MSG
		metrics.IncrServerRequest("admin/Deals",errors.JSON_FAIL)
		return result,nil
	}
	if len(list)<1 {
		list = []*proto.Deal{}
	}
	deals.List = list
	return result, nil
}

type AdminServer struct {
	stop chan int
	signs chan os.Signal
	config configs.AppConfig
}

func (srv *AdminServer) Run(ctx context.Context) error {
	listener, err := net.Listen("tcp", srv.config.Addr)
	if err != nil {
		log.Error("admin net.listen err:%v", err)
		return err
	}
	log.Info(" admin net listening %s",srv.config.Addr)
	AuthFunc := cmd.AuthJWT()
	rpcServer := grpc.NewServer(
		grpc.StreamInterceptor(grpc_auth.StreamServerInterceptor(AuthFunc)),
		grpc.UnaryInterceptor(grpc_auth.UnaryServerInterceptor(AuthFunc)),
	)
	src := new(AdminService)
	proto.RegisterAdminSrvServer(rpcServer,src)
	//proto.RegisterAgentSrvServer(rpcServer,&service.AgentService{})
	signal.Notify(srv.signs, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		select {
		case <-srv.stop:
			rpcServer.Stop()
		case <-srv.signs:
			rpcServer.Stop()
		case <-ctx.Done():
			rpcServer.Stop()
		}
	}()
	fmt.Println("start admin server:",srv.config.Addr)
	err = rpcServer.Serve(listener)
	log.Info("admin grpc server err: %v", err)
	return err
}
func (srv *AdminServer) Close()  {
	close(srv.stop)
}
func NewAdminServer(config configs.AppConfig) *AdminServer{
	server := &AdminServer{}
	server.stop = make(chan int, 1)
	server.signs = make(chan os.Signal, 1)
	server.config = config
	return server
}

